package com.pomelo.tiku.adapters;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

/**
 * @author liuxiangwang
 * @date .
 */
public abstract class BaseAdapter<T> extends RecyclerView.Adapter {
    private List<T> list;
    private Context context;



    public BaseAdapter(List<T> list) {
        this.list = list;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        context = parent.getContext();
        return new ViewHolder(LayoutInflater.from(context).inflate(setLayout(), parent, false));
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, @SuppressLint("RecyclerView") int position) {
        ViewHolder holder1 = (ViewHolder) holder;
        onBindView(list, list.get(position), position, holder1, context, holder1.itemView);
        if (onItemClick != null) {
            holder1.itemView.setOnClickListener(v -> {
                onItemClick.OnItemClick(position,list.get(position));
            });
        }

        if(onItemLongClick != null) {
            holder1.itemView.setOnLongClickListener(view -> {
                onItemLongClick.OnItemLongClick(position,list.get(position));
                return true;
            });
        }
    }

    /**
     * 适合初始加载
     *
     * @param dataList
     */
    public void refreshAdapter(@NonNull List<T> dataList) {
        if (dataList == null) return;
        list.clear();
        list.addAll(dataList);
        notifyDataSetChanged();
    }

    public abstract void onBindView(List<T> list, T data, int pos, RecyclerView.ViewHolder holder, Context context, View view);

    @Override
    public int getItemCount() {
        return list.size();
    }

    public abstract int setLayout();

    public class ViewHolder extends RecyclerView.ViewHolder {
        public ViewHolder(View itemView) {
            super(itemView);
        }
    }

    public OnItemClick onItemClick;
    private OnItemLongClick onItemLongClick;

    public void setOnItemClickListener(OnItemClick onItemClick) {
        this.onItemClick = onItemClick;
    }

    public void setOnItemLongClickListener(OnItemLongClick onItemLongClick) {
        this.onItemLongClick = onItemLongClick;
    }

    public interface OnItemClick<T> {
        void OnItemClick(int pos,T data);

    }

    public interface OnItemLongClick<T> {
        void OnItemLongClick(int pos,T data);
    }
}
